package com.grep.extra.threadpool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.grep.extra.factory.handle.IHandler;

public class ThreadPool<K,T> {

	static Logger logger = LoggerFactory.getLogger(ThreadPool.class);    
	
	//监测线程数的锁
	private Object lock = new Object() ;
	
	private int maxThreadCount = 5 ;
	
	private int threadInit= 5 ;
	
	private int threadCount = 0 ;

	private boolean running = true ;

	public int getMaxThreadCount() {
		return maxThreadCount;
	}

	public void setMaxThreadCount(int maxThreadCount) {
		this.maxThreadCount = maxThreadCount;
	}

	public int getThreadInit() {
		return threadInit;
	}

	public void setThreadInit(int threadInit) {
		this.threadInit = threadInit;
	}

	public ThreadPool(IHandler<K,T> handler) {
    	for(int i = 0 ; i<threadInit ;i++){
    		addThread(handler,-1) ;
    	}
    }
	
	
	public int getThreadCount() {
		synchronized(lock){
			return threadCount;
		}
	}
	/**
	 * 判断并增加线程
	 * @param handler
	 * @param taskCount
	 */
	public void addThread(IHandler<K,T> handler,int taskCount){
		synchronized(lock){
			if(this.threadCount < this.maxThreadCount && (taskCount > 2*this.threadInit || taskCount<0)){
				startThread(handler);
				threadCount++;
			}
		}
	}
	/**
	 * 启动一个新线程
	 * @param handler
	 */
	private void startThread(IHandler<K,T> handler){
		ThreadWorker<K,T> work = new ThreadWorker<K,T>(handler,this) ;
		work.start() ;
	}

	/**
	 * 判断是否需要结束一个线程（用此方法判断并跳出线程处理）
	 * @param taskCount
	 * @return
	 */
    public boolean reduceThread(int taskCount){
    	synchronized(lock){
			if(taskCount < this.threadCount && this.threadCount > this.threadInit){
				threadCount-- ;
				logger.info("[ThreadPool] end a thread :thread id =>"+Thread.currentThread().getId()+
						",Thread name =>" +Thread.currentThread().getName() +
						",task thread count =>" + this.threadCount + ".") ;
				return true ;
			}else{
				return false ;
			}
		}
    }
}
